package cn.cvs.servlet;

import cn.cvs.entity.EdocEntry;
import cn.cvs.service.EdocEntryService;
import cn.cvs.service.impl.EdocEntryServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/list")
public class ListpageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        EdocEntryService service = new EdocEntryServiceImpl();
        Integer pageSize = 2; // 将pageSize修改为2，每页显示两条数据
        if (request.getParameter("pageSize") != null) {
            pageSize = Integer.valueOf(request.getParameter("pageSize"));
        }
        Integer currPage = 1;
        if (request.getParameter("currPage") != null) {
            currPage = Integer.valueOf(request.getParameter("currPage"));
        }

        int startIndex = (currPage - 1) * pageSize;

        Integer totalCount = service.count();

        Integer totalPage = totalCount / pageSize;

        if (totalCount % pageSize != 0) {
            totalPage++;
        }

        List<EdocEntry> list = service.list(startIndex, pageSize);

        request.setAttribute("list", list);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("currPage", currPage);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPage", totalPage);
        request.getRequestDispatcher("list.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
